<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="renderer" content="webkit|ie-comp|ie-stand">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <title>生产订单</title>
</head>

<body>
  <div id="app" v-loading.fullscreen.lock="loading" :element-loading-text="loadingText">
    <div class="create-order" v-if="config!==null">
      <div class="create-order-btns" style="margin-bottom: 5px;">
        <template v-if="mode==='approval'">
          <template v-if="canEdit">
            <el-button size="medium" type="primary" @click="approvalOrder(1)">审核通过</el-button>
            <el-button size="medium" type="danger" @click="approvalOrder(-1)">退回</el-button>
            <el-button size="medium" type="primary" @click="approvalOrder(0)">计划</el-button>
          </template>
        </template>
        <template v-else-if="mode!=='look'&&canEdit">
          <el-button size="medium" type="primary" @click="settingPageConfig">纸张配置</el-button>
          <el-button size="medium" type="primary" @click="createOrder">
            <span v-if="mode==='create'">生成生产订单</span>
            <span v-else>修改生产订单</span>
          </el-button>
          <el-button size="medium" type="primary" @click="changeTemplate">切换模板</el-button>
          <el-button size="medium" type="primary" @click="uploadEnclosure">上传附件</el-button>
        </template>
        <el-button v-if="mode!=='approval'" size="medium" type="primary" @click="printOrder">打印</el-button>
      </div>
      <div class="create-order-content" v-if="produceData!==null" :key="pageId">
        <order-template ref="orderTempl" :config="config" :data="produceData" :is-print="isPrint" :is-line="isLine">
        </order-template>
      </div>
    </div>

    <el-dialog append-to-body :title="dialogTitle" :visible.sync="openDialog" top="10vh" @closed="dialogClosed">
      <div class="dialog-templ">
        <template v-if="openDialog">
          <page-setting v-if="dialogType==='pageSetting'" :config="config" @setting-success="toCloseDialog">
          </page-setting>
          <approval-remark v-else-if="dialogType==='remark'" :data="dialogData" @ensure="toApprovalOrder">
          </approval-remark>
          <upload-enclosure-form v-else-if="dialogType==='upload'" :data="dialogData"></upload-enclosure-form>
        </template>
      </div>
    </el-dialog>

    <el-dialog fullscreen append-to-body class="dialog-fullscreen" title="请选择模板" :visible.sync="openChangeTempl" :close-on-click-modal="false"
      :close-on-press-escape="false" :show-close="config!==null">
      <div style="height:100%;overflow:auto">
        <change-order-template v-if="openChangeTempl" :type="config?'change':'create'" @ensure="toChangeTemplate"></change-order-template>
      </div>
    </el-dialog>
  </div>
</body>

<script src="https://upload.shinehao.com.cn/20181222140744qiniu.min.js"></script>
<script src="https://upload.shinehao.com.cn/20190416085621dom-to-image.min.js"></script>
<script src="../../myJs/importFile.js"></script>
<script>
  importFile([
    "/static/vue-drag-resize/vue-drag-resize.css",
    "/vueSystem/components/css/richEditor.css",
    "/vueSystem/components/css/formGroup.css",
    "/vueSystem/components/css/checkGroup.css",
    "/vueSystem/components/css/showTextarea.css",
    "./components/css/sysDragResize.css",
    "./css/orderInfoSettingDialog.css",
    "./css/orderInfoSetting.css",
    "./css/materialColorSettingDialog.css",
    "./css/materialColorSetting.css",
    "./css/materialSettingDialog.css",
    "./css/materialSetting.css",
    "./css/otherTableItem.css",
    "./css/dragTableSetting.css",
    "./css/pageSetting.css",
    "./css/orderTemplate.css",
    "./css/uploadEnclosureForm.css",
    "./css/changeOrderTemplate.css"
  ], [
    "/vueSystem/i18n/index.js",
    "/static/vue-drag-resize/index.js",
    "/static/vue/qrcode.min.js",
    "/vueSystem/directives/clickoutside.js",
    "/vueSystem/components/formGroup.js",
    "/vueSystem/components/checkGroup.js",
    "/vueSystem/components/showTextarea.js",
    "/vueSystem/models/baseModel.js"
  ]);
  importRichEditorFiles([
    "/vueSystem/components/richEditor.js"
  ]);

</script>

<script src="./models/produceMaterialData.js"></script>
<script src="./models/classifyMaterialData.js"></script>
<script src="./models/produceOrderData.js"></script>
<script src="./models/subsidiaryMaterialData.js"></script>
<script src="./models/materialColorData.js"></script>

<script src="./models/orderInfoConfig.js"></script>
<script src="./models/produceOrderTemplConfig.js"></script>
<script src="./models/materialColorConfig.js"></script>
<script src="./models/materialConfig.js"></script>
<script src="./models/dragConfig.js"></script>
<script src="./mixins/tableResizeMixin.js"></script>

<script src="./components/sysDragResize.js"></script>
<script src="./orderInfoSettingDialog.js"></script>
<script src="./orderInfoSetting.js"></script>
<script src="./materialColorSettingDialog.js"></script>
<script src="./materialColorSetting.js"></script>
<script src="./materialSettingDialog.js"></script>
<script src="./materialSetting.js"></script>
<script src="./otherTableItem.js"></script>
<script src="./dragTableSetting.js"></script>

<script src="./approvalRemark.js"></script>
<script src="./pageSetting.js"></script>
<script src="./orderTemplate.js"></script>
<script src="./uploadEnclosureForm.js"></script>
<script src="./changeOrderTemplate.js"></script>

<script src="./moduleUtil.js"></script>

<script>
  var app = new Vue({
    el: '#app',

    data: function () {
      return {
        loading: false,
        loadingText: '',
        config: null,
        mode: '',
        param: null,
        produceData: null,
        openDialog: false,
        dialogTitle: '',
        dialogType: '',
        dialogData: null,
        isPrint: false,
        isLine: true,
        canEdit: true,
        pageId: SysUtil.getId(),
        eventSource: null,
        isShow: false,
        openChangeTempl: false
      }
    },

    created: function () {
      var param = SysUtil.getPathParam();
      var mode = param.mode;
      this.mode = mode;
      this.param = param;
      if (mode === 'create' && SysUtil.isEmpty(param.templId)) {
        this.openChangeTempl = true;
        return;
      }

      var self = this;
      this.initData().then(function () {
        if (['update', 'approval'].indexOf(mode) !== -1) {
          self.checkEditRunning();
        }
      });
    },

    beforeDestroy: function () {
      var eventSource = this.eventSource;
      if (eventSource !== null) {
        eventSource.close();
      }
    },

    methods: {
      initData: function () {
        var mode = this.mode;
        var param = this.param;
        this.isPrint = ['approval', 'look'].indexOf(mode) !== -1;

        this.loading = true;
        var self = this;
        return ModuleUtil.getProductOrderData(param).then(function (res) {
          self.config = res.config;
          self.produceData = res.orderData;
          self.loading = false;
        }).catch(function (error) {
          console.log('error', error);
          self.loading = false;
        });
      },

      settingPageConfig: function () {
        this.dialogTitle = '纸张设置';
        this.dialogType = 'pageSetting';
        this.openDialog = true;
      },

      toCloseDialog: function () {
        this.openDialog = false;
      },

      dialogClosed: function () {
        this.dialogTitle = '';
        this.dialogType = '';
        this.dialogData = null;
      },

      createOrder: function () {
        this.isPrint = true;
        var self = this;
        this.$nextTick(function () {
          if (!self.checkValid()) {
            self.isPrint = false;
            return;
          }

          var mode = self.mode;
          if (mode === 'create') {
            self.toCreateOrder();
          } else if (mode === 'update') {
            self.toUpdateOrder();
          }
        });
      },

      toCreateOrder: function () {
        this.loading = true;
        var self = this;
        var produceData = this.produceData;
        ModuleUtil.createProduceOrder(this.config, produceData, this).then(function () {
          self.isPrint = false;
          self.loading = false;
          self.loadingText = '';
          self.$alert('生产订单生成成功', '信息', {
            callback: function () {
              var basePath = SysUtil.getBasePath();
              var sysOrderNo = produceData.sysOrderNo;
              location.href = `${basePath}/bomBusiness/produceOrder/createOrder.html?mode=update&sysOrderNo=${sysOrderNo}`;
            }
          });
        }).catch(function () {
          self.isPrint = false;
          self.loading = false;
          self.loadingText = '';
        });
      },

      toUpdateOrder: function () {
        this.loading = true;
        var self = this;
        ModuleUtil.updateProduceOrder(this.config, this.produceData, this).then(function () {
          self.isPrint = false;
          self.loading = false;
          self.loadingText = '';
          self.$alert('生产订单修改成功', '信息');
        }).catch(function () {
          self.isPrint = false;
          self.loading = false;
          self.loadingText = '';
        });
      },

      checkValid: function () {
        var config = this.config;
        var code = config.checkValid();
        if (code !== '') {
          var msg = i18n.getMsg(`produceOrder.error.${code}`);
          this.$alert(msg);
          return false;
        }

        if (!this.$refs.orderTempl.checkValid()) {
          return false;
        }

        var produceData = this.produceData;
        code = produceData.checkValid();
        if (code !== '') {
          var msg = i18n.getMsg(`produceOrder.error.${code}`);
          this.$alert(msg);
          return false;
        }

        return true;
      },

      approvalOrder: function (status) {
        this.dialogTitle = '备注';
        this.dialogType = 'remark';
        this.dialogData = {
          status: status
        };
        this.openDialog = true;
      },

      toApprovalOrder: function (data, remark) {
        var status = data.status;
        var produceData = this.produceData;
        var option = {
          remark: remark,
          status: status
        };

        if (status === 1) {
          option.el = this.$refs['orderTempl'].$el;
          this.isLine = false;
        }

        var self = this;
        this.$nextTick(function () {
          self.loading = true;
          ModuleUtil.approvalProduceOrder(produceData, option, this).then(function () {
            var msg = '';
            if (status === 1) {
              msg = '成功审核通过';
            } else if (status === -1) {
              msg = '成功退回';
            } else if (status === 0) {
              msg = '成功计划';
            }
            self.$alert(msg, '信息', {
              callback: function () {
                var basePath = SysUtil.getBasePath();
                var sysOrderNo = produceData.sysOrderNo;
                location.href = `${basePath}/bomBusiness/produceOrder/createOrder.html?mode=look&sysOrderNo=${sysOrderNo}`;
              }
            });
            self.isLine = true;
            self.loading = false;
            self.loadingText = '';
            self.openDialog = false;
          }).catch(function (errorMsg) {
            if (typeof errorMsg === 'string') {
              self.$alert(errorMsg, '信息');
            }
            self.loading = false;
            self.loadingText = '';
            self.isLine = true;
          });
        });
      },

      uploadEnclosure: function () {
        this.dialogTitle = '上传附件';
        this.dialogType = 'upload';
        var sysOrderNo = this.produceData.sysOrderNo
        this.dialogData = {
          sysOrderNo: sysOrderNo
        };
        this.openDialog = true;
      },

      printOrder: function () {
        var mode = this.mode;
        var flag = ['look', 'approval'].indexOf(mode) === -1 && this.canEdit;
        if (flag) {
          this.isPrint = true;
        }

        var self = this;
        this.$nextTick(function () {
          self.toPrintOrder().then(function () {
            if (flag) {
              self.isPrint = false;
            }
          });
        });
      },

      toPrintOrder: function () {
        if (!this.checkValid()) {
          return Promise.resolve(true);
        }

        var sysOrderNo = this.produceData.sysOrderNo;
        this.loading = true;
        var self = this;
        return new Promise(function (resole) {
          ajaxRequest('createOrder/operateLog', {
            type: 1,
            order_no: sysOrderNo
          }).then(function () {
            self.loading = false;
            self.$nextTick(function () {
              var $printEl = $(self.$refs['orderTempl'].$el);
              $printEl = $printEl.clone();
              $printEl.css('display', 'none');
              $('#app').append($printEl);
              window.print();
              $printEl.remove();
              resole(true);
            });
          }).catch(function () {
            resole(false);
          });
        });
      },

      checkEditRunning: function () {
        if (window.EventSource) {
          var basePath = SysUtil.getBasePath();
          var produceData = this.produceData;
          var sysOrderNo = produceData.sysOrderNo;
          var source = new EventSource(basePath + '/sse/isOperateOrder?orderNo=' + sysOrderNo);

          var self = this;
          source.addEventListener('message', function (e) {
            var data = e.data;
            if (data.length === 0) {
              return;
            }

            if (self.canEdit) {
              self.canEdit = false;
              self.isPrint = true;
              var jsonData = JSON.parse(data);
              self.$alert("当前订单已经由 [" + jsonData.loginUserName + "] 操作中,您当前只有查看功能");
            }
          });

          source.addEventListener('error', function (e) {
            if (e.readyState === EventSource.CLOSED) {
              console.log("Connection is closed");
            }
          }, false);
          self.eventSource = source;
        } else {
          this.$alert("Your web browser dosen't support EventSource.");
        }
      },

      changeTemplate: function () {
        this.openChangeTempl = true;
      },

      toChangeTemplate: function (templId, type) {
        var param = this.param;
        param.templId = templId;
        if (type === 'create') {
          this.openChangeTempl = false;
          this.initData();
          return;
        }

        this.loading = true;
        var self = this;
        return ModuleUtil.getProductOrderData(param).then(function (res) {
          self.config = res.config;
          self.produceData = res.orderData;
          self.pageId = SysUtil.getId();
          self.openChangeTempl = false;
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      }
    },

    components: {
      PageSetting: PageSetting,
      OrderTemplate: OrderTemplate,
      ApprovalRemark: ApprovalRemark,
      UploadEnclosureForm: UploadEnclosureForm,
      ChangeOrderTemplate: ChangeOrderTemplate
    }
  });

</script>

<style>
  .create-order {
    padding: 10px 20px 5px;
    height: calc(100% - 15px);
    overflow: auto;
    display: flex;
    flex-direction: column;
  }

  .create-order .create-order-content {
    position: relative;
    flex: 1;
    overflow: auto;
  }

  .dialog-templ {
    height: calc(80vh - 54px);
    overflow: auto;
  }

  @media print {

    html,
    body,
    #app {
      height: auto !important;
      overflow: visible !important;
    }

    #app>div {
      display: none !important;
    }

    #app>.order-template {
      display: block !important;
    }

    .order-template .order-template-line,
    .drag-table-setting .drag-table-setting-line,
    .sys-drag-resize .sys-drag-resize-line {
      display: none !important;
    }

    .material-color-setting .material-color-setting-line,
    .material-setting-item .material-setting-item-line {
      z-index: 1 !important;
    }

    .material-setting-item .el-table--border::after,
    .material-setting-item .el-table--group::after,
    .material-setting-item .el-table::before {
      background: none !important;
    }

    .material-color-setting .el-table--border::after,
    .material-color-setting .el-table--group::after,
    .material-color-setting .el-table::before {
      background: none !important;
    }

    .material-setting .material-setting-line {
      display: none !important;
    }
  }

</style>

</html>
